package com.share.interceptor;

import cn.hutool.jwt.JWTUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.share.constant.LogInfo;
import com.share.holder.LogContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.FileWriter;
import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;

import static com.share.constant.DefaultConstant.*;

@Component
public class LogInterceptor implements HandlerInterceptor {


    private final ObjectMapper objectMapper;

    @Autowired
    public LogInterceptor(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 记录请求日志
        LogInfo logInfo = new LogInfo();
        logInfo.setRequestTime(LocalDateTime.now());
        logInfo.setRequestUrl(request.getRequestURI());
        logInfo.setRequestIp(request.getRemoteAddr());

        // 从token中获取用户id
        String token = request.getHeader(TOKEN_KEY);
        if (token != null && !token.isEmpty()) {
            try {
                logInfo.setUserId(JWTUtil.parseToken(token).getPayload(USERNAME_ID).toString());
            } catch (Exception e) {
                logInfo.setUserId("Unknown"); // 如果无法解析token，设置为未知
            }
        } else {
            logInfo.setUserId("No Token");
        }

        // 将LogInfo放入ThreadLocal中
        LogContextHolder.set(logInfo);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 记录响应日志
        LogInfo logInfo = LogContextHolder.get();
        if (logInfo != null) {
            logInfo.setResponseStatusCode(response.getStatus());
            logInfo.setResponseTime(Duration.between(logInfo.getRequestTime(), LocalDateTime.now()).toMillis());

            // 写入日志文件
            writeLogToFile(logInfo.toString());

            // 清理ThreadLocal中的数据
            LogContextHolder.clear();
        }
    }

    private void writeLogToFile(String logMessage) {
        try (FileWriter fileWriter = new FileWriter(LOG_FILE_PATH, true)) {
            fileWriter.write(logMessage + System.lineSeparator());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


